package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ShoppingCartServiceimpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {


    /**
     * 向购物车中添加菜品
     * @param shoppingCart
     * @return
     */
    @Override
    public Boolean add(ShoppingCart shoppingCart) {
        //设置当前用户ID
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);
        //查询当前菜品或者套餐是否在购物车当中？
        Long dishId = shoppingCart.getDishId(); //菜品ID

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);

        if (dishId!=null){
            //添加到购物车当中的是菜品
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }else {
            //否则就是套餐ID
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart one = this.getOne(queryWrapper);
         if (one!=null){
             //如果已经存在就在数量+1
             Integer number = one.getNumber() + 1;
             one.setNumber(number);
             boolean b = this.updateById(one);
             return b;
         }else {
             //如果不存在就添加到购物车数量默认就是1
             boolean save = this.save(shoppingCart);
             return  save;
         }
        }
    }

